<template>
  <Category :scene="scene"></Category>
  <el-card style="margin-top: 10px 0px">
    <div v-if="scene == 0">
      <el-button
        type="primary"
        size="default"
        :icon="Plus"
        @click="addAttr"
        :disabled="categoryStore.c3Id ? false : true"
        >添加平台属性</el-button
      >
      <el-table
        border
        style="margin-top: 10px"
        :data="attrList"
        v-if="attrList.length > 0"
      >
        <el-table-column
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column
          label="属性名称"
          prop="attrName"
          width="150px"
        ></el-table-column>
        <el-table-column label="属性值名称">
          <template #="{ row, $index }">
            <el-tag
              v-for="(attrValue, index) in row.attrValueList"
              :key="attrValue.id"
              style="margin: 5px"
              class="ml-2"
              :type="attrValue.id % 2 == 0 ? 'success' : 'warning'"
              >{{ attrValue.valueName }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150px">
          <template #="{ row, $index }">
            <el-button
              type="warning"
              size="default"
              :icon="Edit"
              @click="updataAttr(row)"
            ></el-button>
            <el-popconfirm
              :title="`你确定要删除${row.attrName}?`"
              width="250px"
              @confirm="deleteAttr(row.id)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="default"
                  :icon="Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-empty
        v-else
        :image-size="400"
        description="数据正在加载中..."
        image="http://139.198.127.41:9000/sph/20231204/2.gif"
      />
    </div>
    <div v-else>
      <el-form :inline="true">
        <el-form-item label="属性名称">
          <el-input
            placeholder="请输入属性名字"
            v-model="attrParams.attrName"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        size="default"
        :icon="Plus"
        :disabled="attrParams.attrName ? false : true"
        @click="addAttrValue"
        >添加属性值</el-button
      >
      <el-button @click="cancel">取消</el-button>
      <el-table
        border
        style="margin: 10px 0px"
        :data="attrParams.attrValueList"
      >
        <el-table-column label="序号" width="80px" type="index" align="center">
        </el-table-column>
        <el-table-column label="属性值">
          <template #="{ row, $index }">
            <el-input
              ref="inputObj"
              v-if="row.showInput"
              @blur="toLook(row, $index)"
              v-model="row.valueName"
              placeholder="请输入属性值"
            ></el-input>
            <div v-else @click="toEdit(row)">{{ row.valueName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #="{ row, $index }">
            <el-popconfirm
              :title="`你确定要删除${row.valueName}`"
              width="250"
              @confirm="attrParams.attrValueList.splice($index, 1)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="small"
                  :icon="Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-button
        type="primary"
        size="default"
        @click="save"
        :disabled="attrParams.attrValueList.length ? false : true"
        >保存</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
// 导入icon组件
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import { watch, ref, reactive, nextTick } from "vue";
// 获取分类的仓库
import useCategoryStore from "@/stores/catrgory";

// 导入请求方法
import {
  reqAttrList,
  reqAddOrUpdateAttr,
  reqDeleteAttr,
} from "@/api/product/attr";
// 导入进去接口的文件
import type { Attrs, Attr, AttrValue } from "@/api/product/attr/type";

//
import cloneDeep from "lodash/cloneDeep";

//
import { ElMessage } from "element-plus";

//
const inputObj = ref<any>();

// 存储已有的属性与属性值
const attrList = ref<Attrs>([]);
// 定义一个响应式数据控制卡片的切换
const scene = ref<number>(0);

// 创建仓库的实例化对象
const categoryStore = useCategoryStore();

//
const attrParams = reactive<Attr>({
  attrName: "",
  attrValueList: [],
  categoryId: 0,
  categoryLevel: 3,
});

//  watch监听三级分类的变化
watch(
  () => categoryStore.c3Id,
  () => {
    //三级分类的变化
    attrList.value = [];
    categoryStore.c3Id && getAttrList();
  }
);

// 定义发送请求的回调函数
const getAttrList = async () => {
  // 获取平台属相与属性值
  const { c1Id, c2Id, c3Id } = categoryStore;
  // 发送请求
  let result: Attrs = await reqAttrList(c1Id, c2Id, c3Id);

  // 请求到的数据存储一下
  attrList.value = result;
};
// 点击添加成功回调的函数
const addAttr = () => {
  // 清空数组
  reset();
  // 场景数量变1
  scene.value = 1;
  // 收集新增属性
  attrParams.categoryId = categoryStore.c3Id as number;
};
// 点击取消的按钮
const cancel = () => {
  scene.value = 0;
};
// 添加属性的回调函数
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: "",
    showInput: true,
  });
  nextTick(() => {
    inputObj.value.focus();
  });
};
// 点击保存的回调函数
const save = async () => {
  // 整理参数
  // 发送请求
  try {
    // 添加获取更新成功
    await reqAddOrUpdateAttr(attrParams);
    // 添加成功的回调函数
    ElMessage({
      type: "success",
      message: attrParams.id ? "更新成功" : "添加成功",
    });
    // 切换场景为0
    scene.value = 0;
    // 重新发送请求
    getAttrList();
  } catch (error) {
    ElMessage({
      type: "error",
      message: attrParams.id ? "更新失败" : "添加失败",
    });
  }
};
// 清空参数的回调函数
const reset = () => {
  Object.assign(attrParams, {
    attrName: "",
    attrValueList: [],
    categoryId: 0,
    categoryLevel: 3,
  });
};
// input组件:变成查看模式
const toLook = (row: AttrValue, index: number) => {
  // 非法清空判断:属性值不能能为空
  if (row.valueName.trim() == "") {
    // 提示信息
    ElMessage({
      type: "error",
      message: "属性值不能为空",
    });
    attrParams.attrValueList.splice(index, 1);
    // 出现非法的情况:后面语句不在执行
    return;
  }
  // 属性重复的变化
  let repeat = attrParams.attrValueList.find((allAttrValue) => {
    // 将自身从数组当中排除
    if (row != allAttrValue) {
      return row.valueName === allAttrValue.valueName;
    }
  });
  // 重复的判断
  if (repeat) {
    ElMessage({
      type: "error",
      message: "属性值不能重复",
    });
    attrParams.attrValueList.splice(index, 1);
    return;
  }
  row.showInput = false;
};

const toEdit = (row: AttrValue) => {
  row.showInput = true;
  nextTick(() => {
    inputObj.value.focus();
  });
};
// 更新已有的属性的回调函数
const updataAttr = (attr: Attr) => {
  scene.value = 1;
  Object.assign(attrParams, cloneDeep(attr));
};
// 删除已有的属性的回调函数
const deleteAttr = async (id: number) => {
  try {
    // 发送请求
    await reqDeleteAttr(id);
    // 删除成功的提示信息
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    // 重新获取数据
    getAttrList();
  } catch (error) {
    ElMessage({
      type: "error",
      message: "删除失败",
    });
  }
};
</script>

<script lang="ts">
export default {
  name: "Attr",
};
</script>

<style scoped></style>
